#include <stdio.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

#include <string.h>
#include <errno.h>

// ./cp1 <file1> <file2>
int main(int argc, char const *argv[])
{
    if(argc != 3) return -1;
    int fd1 = open(argv[1], O_RDONLY);
    if(fd1 < 0){
        printf("%s open fail: %s\n", argv[1], strerror(errno));
        return -1;
    }

    int fd2 = open(argv[2], O_CREAT|O_WRONLY|O_TRUNC, 0644);
    
    int active_num; // 存储select()函数返回的结果, 选择读集和写集中的可用FD的数量
    fd_set read_set, write_set; 
    char buf[512] = ""; // 缓冲区

    while(1){
        // 清空Select的读集和写集
        FD_ZERO(&read_set);
        FD_ZERO(&write_set);

        // 将fd1,fd2分别添加 到读集和写集中
        FD_SET(fd1, &read_set);
        FD_SET(fd2, &write_set);

        // 选择可读或读写的FD
        active_num = select(fd2+1, &read_set, &write_set, NULL, NULL);
        if(active_num == -1){
            perror("select");
            break;
        }
        printf("active_fd is %d\n", active_num);

        if(FD_ISSET(fd1, &read_set)){
            ssize_t len = read(fd1, buf, 512);  // 0,EOF(-1)
            if(len <= 0) break;
        }

        if(FD_ISSET(fd2, &write_set)){
            write(fd2, buf, strlen(buf));
        }
    }

    close(fd1);
    close(fd2);
    printf("OK\n");
    return 0;
}
